package com.ryzx.jpa.helper.base;

import com.ryzx.common.feign.IDGeneratorFeign;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;
import org.springframework.context.annotation.Lazy;

import java.io.Serializable;

public class GenerateSnowflakeId implements IdentifierGenerator {


    private final IDGeneratorFeign idGeneratorFeign;

    @Lazy
    public GenerateSnowflakeId(IDGeneratorFeign idGeneratorFeign) {
        this.idGeneratorFeign = idGeneratorFeign;
    }

    @Override
    public Serializable generate(SharedSessionContractImplementor sharedSessionContractImplementor, Object o) throws HibernateException {
        BapBaseEntity entity=(BapBaseEntity)o;
        Long id=entity.getId();
        if (id != null) {
            return id;
        }
        return idGeneratorFeign.nextId();
    }
}